import { config } from 'config.js'
const app = getApp()
class HTTP {
  request(params){
    if(!params.methods){
      params.methods = 'GET'
    }
    
    //加载提示
    wx.showLoading({
      title: '数据加载中...',
    });
    wx.request({
      url: config.url + params.url,
      data: params.data,
      method: params.methods,
      dataType: 'json',
      header: { Authorization: wx.getStorageSync('token')},
      responseType: 'text',
      success: function(res) {
        wx.hideLoading();
        if (res.data.code == 10000){
          params.success(res.data)
        } else if (res.data.code == 10006 || res.data.code == 10002){ 
          if (params.url == 'mini/v1/personal/info' && params.data == undefined){
            return false;
          }

          if (params.url == 'mini/v1/personal/my_works' || params.url == 'mini/v1/personal/my_photo' ||  params.url == 'mini/v1/personal/business_card') {
            return false;
          }

          wx.showModal({
            title: '提示',
            content: '登录后才可查看操作，是否进行登录?',
            confirmColor: '#f45859',
            confirmText: '去登录',
            success(res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/other/login/login',
                  success: res => { 
                    
                  },
                },
                );
              } else if (res.cancel) {
                wx.navigateBack({ changed: true });
              }
            }
          })
          
        } else if (res.data.code == 20006){ //验证码失效
          wx.removeStorageSync('token');
          wx.removeStorageSync('region_name');
          wx.removeStorageSync('checklogin');
          wx.removeStorageSync('checkcity');
          wx.removeStorageSync('region_id');
          wx.removeStorageSync('code');
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 1500
          });
          setTimeout(function(){
            wx.login({
              success: res => {
                wx.removeStorageSync('code');
                wx.setStorage({
                  key: 'code',
                  data: res.code
                });
              }
            });
          },100) 

        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function(res) {
        wx.hideLoading();
        wx.showToast({
          title: '网络繁忙，请稍后再试！',
          icon: 'none',
          duration: 1000
        });
      }
    })
  }
}

export { HTTP }